package com.psnoted.backend.controller;

import com.psnoted.backend.dto.ApiResponse;
import com.psnoted.backend.dto.UnifiedVerificationRequest;
import com.psnoted.backend.dto.UnifiedVerificationResponse;
import com.psnoted.backend.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 提供统一验证的REST API接口
 * 
 * @author PSNoted Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "认证管理", description = "统一验证相关接口")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    /**
     * 统一验证接口
     * 根据密钥哈希自动判断用户状态，新用户自动注册，老用户验证身份
     * 
     * @param request 统一验证请求
     * @return 统一验证结果
     */
    @PostMapping("/verify")
    @Operation(
        summary = "统一验证接口",
        description = "根据密钥哈希自动判断用户状态，新用户自动注册，老用户验证身份"
    )
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "验证成功",
            content = @Content(schema = @Schema(implementation = UnifiedVerificationResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "400",
            description = "请求参数错误",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "500",
            description = "服务器内部错误",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        )
    })
    public ResponseEntity<ApiResponse<UnifiedVerificationResponse>> verifyUnified(
            @Parameter(description = "统一验证请求", required = true)
            @Valid @RequestBody UnifiedVerificationRequest request) {
        
        logger.info("收到统一验证请求: keyHash={}, username={}", request.getKeyHash(), request.getUsername());
        
        try {
            UnifiedVerificationResponse response = authService.verifyUnified(request);
            
            String message = response.isNewUser() ? "新用户注册成功" : "用户验证成功";
            logger.info("统一验证成功: keyHash={}, isNewUser={}", request.getKeyHash(), response.isNewUser());
            return ResponseEntity.ok(ApiResponse.success(message, response));
        } catch (Exception e) {
            logger.error("统一验证异常: keyHash={}, error={}", request.getKeyHash(), e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ApiResponse.error("统一验证失败: " + e.getMessage()));
        }
    }



    /**
     * 检查用户是否存在
     * 
     * @param keyHash 密钥哈希
     * @return 检查结果
     */
    @GetMapping("/check-user/{keyHash:.+}")
    @Operation(
        summary = "检查用户是否存在",
        description = "根据密钥哈希检查用户是否已存在"
    )
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "检查成功",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "400",
            description = "请求参数错误",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        )
    })
    public ResponseEntity<ApiResponse<Boolean>> checkUserExists(
            @Parameter(description = "密钥哈希", required = true)
            @PathVariable String keyHash) {
        
        logger.info("检查用户是否存在: keyHash={}", keyHash);
        
        try {
            boolean exists = authService.userExists(keyHash);
            String message = exists ? "用户已存在" : "用户不存在";
            
            return ResponseEntity.ok(ApiResponse.success(message, exists));
        } catch (Exception e) {
            logger.error("检查用户存在异常: keyHash={}, error={}", keyHash, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ApiResponse.error("检查用户失败: " + e.getMessage()));
        }
    }

    /**
     * 健康检查接口
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    @Operation(
        summary = "健康检查",
        description = "检查认证服务是否正常运行"
    )
    public ResponseEntity<ApiResponse<String>> health() {
        logger.debug("健康检查请求");
        return ResponseEntity.ok(ApiResponse.success("认证服务运行正常", "OK"));
    }
} 